package com.stylefeng.guns.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.modular.system.dao.OrgMapper;
import com.stylefeng.guns.modular.system.model.Org;
import com.stylefeng.guns.modular.system.service.IOrgService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统组织机构 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-08-24
 */
@Service
@CacheConfig(cacheNames = "local")
@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements IOrgService {


    @Resource
    private OrgMapper orgMapper;

    @Override
    @Cacheable(key = "'orgList_1'+#p0",unless = "#result.size()==0")
    public List<Map<String, Object>> list(String condition)throws DataAccessException {
        return this.baseMapper.list(condition);
    }

    /**
     * 获取机构列表
     */
    @Override
    @Cacheable(key = "'orgList_2'+#p0",unless = "#result.size()==0")
    public List<Map<String, Object>> selectOrgList(String condition)throws DataAccessException {
        return this.baseMapper.selectOrgList(condition);
    }

    @Override
    @Cacheable(key = "'orgList_3'+#root.methodName",unless = "#result.size()==0")
    public List<Org> selectListOrg(Org org)throws DataAccessException {
        return orgMapper.selectListOrg(org);
    }

    @Override
    @Cacheable(key = "'orgList_4'+#soName",unless = "#result.size()==0")
    public List<ZTreeNode> tree(String soName)throws DataAccessException {
        return this.baseMapper.tree(soName);
    }

    /**
     * 删除组织机构
     *
     * @param soId
     */
    @Override
    @CacheEvict(allEntries = true,beforeInvocation=true)
    public void deleteOrg(Integer soId) throws DataAccessException{
        Org org = orgMapper.selectById(soId);

        Wrapper<Org> wrapper = new EntityWrapper<>();
        wrapper = wrapper.like("so_pids", "%[" + org.getSoId() + "]%");
        List<Org> subDepts = orgMapper.selectList(wrapper);
        for (Org temp : subDepts) {
            temp.deleteById();
        }

        org.deleteById();
    }
}
